import { List, MenuProps } from 'antd'
import UserMenuItem, { AppMenuItemAction } from './UserMenuItem'
import { MenuItemType } from 'antd/es/menu/hooks/useItems'
import React, { ReactNode, useEffect, useState } from 'react'
interface AppMenuItemType extends MenuItemType {

}
interface ClickInfo {
    key: string;
    domEvent: React.MouseEvent<HTMLElement, MouseEvent>
}
export declare type AppMenuClickEventHandler = (info: ClickInfo) => void
interface AppMenuProps extends Omit<MenuProps, 'items' | 'onClick'> {
    actions?: AppMenuItemAction[];
    items?: AppMenuItemType[]
    actionIcon?: ReactNode
    onClick?: AppMenuClickEventHandler
    defaultSelectedKey?: string
    selectedKey?: string
}
const UserMenu: React.FC<AppMenuProps> = (props) => {
    const [selectedKey, setSelectedKey] = useState<string>(props.defaultSelectedKey || '0')
    useEffect(() => {
        if (props.selectedKey) {
            setSelectedKey(props.selectedKey)
        }
    }, [props.selectedKey])
    return (
        <>
           <List
                itemLayout="horizontal"
                dataSource={props.items}
                renderItem={(i) => (
                    <UserMenuItem
                        onClick={(e) => {
                            setSelectedKey(i.key.toString())
                            if (props.onClick) {
                                props.onClick({
                                    key: i.key.toString(),
                                    domEvent: e,
                                })
                            }
                        }}
                        selected={i.key.toString() === selectedKey}
                        key={i.key}
                        icon={i.icon}
                        actionIcon={props.actionIcon}
                        actions={props.actions}
                    >
                        {i?.label}
                    </UserMenuItem>
                )}
            />
        </>
    )
}

export default UserMenu